<template>
  <el-dialog
    v-model="visible"
    title="作业项管理"
    width="600px"
    @close="resetForm"
  >
    <!-- 作业状态提示 -->
    <div v-if="homework" class="status-notice">
      <el-alert
        :title="statusNotice.title"
        :type="statusNotice.type"
        :description="statusNotice.description"
        :closable="false"
        show-icon
      />
    </div>

    <!-- 快速添加作业项 -->
    <div class="quick-add-section" v-if="!isReadOnly">
      <el-form :model="newDetail" label-width="80px">
        <el-form-item label="新作业项">
          <div class="quick-add-input">
            <el-input
              v-model="newDetail.content"
              placeholder="输入作业内容"
              style="flex: 1"
              @keyup.enter="handleQuickAdd"
            />
            <el-select
              v-model="newDetail.isRequired"
              style="width: 100px; margin-left: 10px"
            >
              <el-option label="必须" :value="true" />
              <el-option label="可选" :value="false" />
            </el-select>
            <el-button
              type="primary"
              size="small"
              @click="handleQuickAdd"
              style="margin-left: 10px"
              :disabled="!newDetail.content.trim()"
            >
              添加
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 作业明细列表 -->
    <div class="details-list">
      <div
        v-for="(detail, index) in details"
        :key="detail.id"
        class="detail-item"
        :class="{ 'detail-completed': detail.isCompleted }"
      >
        <div class="detail-header">
          <div class="detail-info">
            <span class="detail-index">#{{ index + 1 }}</span>
            <el-tag
              :type="detail.isRequired ? 'danger' : 'info'"
              size="small"
              style="margin-left: 8px"
            >
              {{ detail.isRequired ? '必须' : '可选' }}
            </el-tag>
            <el-tag
              v-if="detail.isCompleted"
              type="success"
              size="small"
              style="margin-left: 4px"
            >
              已完成
            </el-tag>
          </div>
          <div class="detail-actions">
            <el-button
              v-if="!detail.isCompleted && !isReadOnly"
              type="primary"
              size="small"
              @click="startEditDetail(detail)"
            >
              编辑
            </el-button>
            <el-button
              v-if="!detail.isCompleted && !isReadOnly"
              type="danger"
              size="small"
              @click="handleDeleteDetail(detail)"
            >
              删除
            </el-button>
          </div>
        </div>
        <div class="detail-content">
          {{ detail.content }}
        </div>
        <div v-if="detail.completedTime" class="detail-complete-time">
          完成时间：{{ formatTime(detail.completedTime) }}
        </div>
      </div>
    </div>

    <!-- 编辑作业项对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑作业项"
      width="400px"
      append-to-body
    >
      <el-form :model="editingDetail" label-width="80px">
        <el-form-item label="内容">
          <el-input
            v-model="editingDetail.content"
            placeholder="输入作业内容"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="editingDetail.isRequired" style="width: 100%">
            <el-option label="必须完成" :value="true" />
            <el-option label="非必须" :value="false" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateDetail" :loading="updating">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useHomeworkStore } from '@/store/homework'
import dayjs from 'dayjs'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  homework: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const homeworkStore = useHomeworkStore()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 作业状态相关
const homeworkStatus = computed(() => props.homework?.status || 0)
const isReadOnly = computed(() => homeworkStatus.value === 2)

// 状态提示信息
const statusNotice = computed(() => {
  switch (homeworkStatus.value) {
    case 0:
      return {
        title: '作业未开始',
        type: 'info',
        description: '可以添加、编辑或删除任何作业项。'
      }
    case 1:
      return {
        title: '作业进行中',
        type: 'warning',
        description: '可以添加新作业项，编辑或删除未完成的作业项。已完成的作业项不能修改。'
      }
    case 2:
      return {
        title: '作业已完成',
        type: 'success',
        description: '作业已完成，当前为只读模式。'
      }
    default:
      return { title: '', type: 'info', description: '' }
  }
})

// 数据状态
const details = ref([])
const newDetail = ref({ content: '', isRequired: true })
const editDialogVisible = ref(false)
const editingDetail = ref({ id: null, content: '', isRequired: true })
const updating = ref(false)

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 重置表单
const resetForm = () => {
  details.value = []
  newDetail.value = { content: '', isRequired: true }
  editingDetail.value = { id: null, content: '', isRequired: true }
}

// 加载作业明细
const loadDetails = async () => {
  if (!props.homework) return

  try {
    const response = await homeworkStore.fetchHomeworkDetails(props.homework.id)
    details.value = response.data || []
  } catch (error) {
    console.error('加载作业明细失败:', error)
    ElMessage.error('加载作业明细失败')
  }
}

// 快速添加作业项
const handleQuickAdd = async () => {
  if (!newDetail.value.content.trim()) return

  try {
    await homeworkStore.addHomeworkDetail(props.homework.id, {
      content: newDetail.value.content.trim(),
      isRequired: newDetail.value.isRequired
    })

    // ElMessage.success('作业项添加成功')
    newDetail.value = { content: '', isRequired: true }
    await loadDetails()
    emit('success')
  } catch (error) {
    console.error('添加作业项失败:', error)
    ElMessage.error(error.message || '添加作业项失败')
  }
}

// 开始编辑作业项
const startEditDetail = (detail) => {
  editingDetail.value = {
    id: detail.id,
    content: detail.content,
    isRequired: detail.isRequired
  }
  editDialogVisible.value = true
}

// 更新作业项
const handleUpdateDetail = async () => {
  if (!editingDetail.value.content.trim()) {
    ElMessage.error('请输入作业内容')
    return
  }

  updating.value = true
  try {
    await homeworkStore.updateHomeworkDetail(
      props.homework.id,
      editingDetail.value.id,
      {
        content: editingDetail.value.content.trim(),
        isRequired: editingDetail.value.isRequired
      }
    )

    ElMessage.success('作业项更新成功')
    editDialogVisible.value = false
    await loadDetails()
    emit('success')
  } catch (error) {
    console.error('更新作业项失败:', error)
    ElMessage.error(error.message || '更新作业项失败')
  } finally {
    updating.value = false
  }
}

// 删除作业项
const handleDeleteDetail = async (detail) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除作业项"${detail.content}"吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await homeworkStore.deleteHomeworkDetail(props.homework.id, detail.id)
    // ElMessage.success('作业项删除成功')
    await loadDetails()
    emit('success')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除作业项失败:', error)
      ElMessage.error(error.message || '删除作业项失败')
    }
  }
}

// 监听作业变化
watch(() => props.homework, (homework) => {
  if (homework) {
    loadDetails()
  }
}, { immediate: true })
</script>

<style scoped>
.status-notice {
  margin-bottom: 20px;
}

.quick-add-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.quick-add-input {
  display: flex;
  align-items: center;
}

.details-list {
  max-height: 400px;
  overflow-y: auto;
}

.detail-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 10px;
  transition: all 0.3s ease;
}

.detail-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.1);
}

.detail-completed {
  background-color: #f0f9ff;
  border-color: #bfdbfe;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.detail-info {
  display: flex;
  align-items: center;
}

.detail-index {
  font-weight: bold;
  color: #409eff;
}

.detail-actions {
  display: flex;
  gap: 8px;
}

.detail-content {
  font-size: 14px;
  line-height: 1.5;
  color: #303133;
  margin-bottom: 8px;
}

.detail-complete-time {
  font-size: 12px;
  color: #909399;
}
</style>